import React, { useEffect, useState } from 'react'
import TodoHeader from '../../components/TodoHeader/TodoHeader'
import TodoMain from '../../components/TodoMain/TodoMain'
import TodoFooter from '../../components/TodoFooter/TodoFooter'
import {nanoid} from 'nanoid'
import axios from '../../http' 

import {reqTodo,reqAddTodo,reqDeleteTodo,reqUpdateTodo, reqAllTodo,reqClearok} from "../../api/todo"

import './TodoList.css'
export default function TodoList() {
let [data,setData] = useState([
 
]) 

// console.log(reqTodo);
// 添加一个数据

let addTodo = async(title) => {
  let res = await reqAddTodo(title)
  setData(
    [
      ...data,
      res
    ]
  )
}
// 删除一个数据
let deleteTodo =async(id) => {
    await reqDeleteTodo(id)
    let newdata = data.filter((item) => item.id !== id);
    setData(newdata);
}
// 修改数据

let updateTodo = async (id,done) => {
  await reqUpdateTodo(id,done);
  let newdata = data.map((item) => {
      if(item.id === id){
         item.done = done;
      }
      return item ;
  })
  setData(newdata)
}

// 全选全不选
let allTodo = async(done) => {
  await reqAllTodo(data,done)
  let newdata = data.map((item) => {
    item.done = done
    return item
  })
  setData(newdata)
}

// 清除所有以完成数据
let clearOk = async () => {
    await  reqClearok(data);
    let newdata = data.filter((item) => !item.done)
    setData(newdata)
}
useEffect(() => {
  // addTodo('放假了')
  // deleteTodo(3)
  // updateTodo(1,false)
  // allTodo(false)
  // clearOk();
  (async() => {
    let res =  await reqTodo();
    setData(res)
  })()
},[])

  return (
  <div className="todo-container">
    <div className="todo-wrap">
        <TodoHeader addTodo={addTodo}/>
        <TodoMain data={data} deleteTodo={deleteTodo} updateTodo={updateTodo}/>
        <TodoFooter data={data} allTodo={allTodo} clearOk={clearOk}/>
    </div>
  </div>
  )
}
